package com.xhwl.centiotdata.suppliersystem.virtualDevice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.dto.dahua.DeviceDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.device.DeviceIntegrationConfigDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class VirtualDeviceHandler {
    private static final Logger log = LoggerFactory.getLogger(VirtualDeviceHandler.class);

    @Autowired
    private GeneralVirtualDeviceHandler generalVirtualDeviceHandler;

    public static final String GET_DEVICE_URL = "/getdevice/";

    public List<DeviceDaHuaDTO> pullDevice(DeviceIntegrationConfigDTO configDTO) {

        HashMap<String, Object> params = new HashMap<>();
        params.put("pageNum", 1);
        params.put("pageSize", 500);

        JSONObject resultObject = generalVirtualDeviceHandler.get(GET_DEVICE_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null) {
            return null;
        }
        if ("false".equals(resultObject.getString("success"))) {
            log.error("post path:{};params:{};errMsg:{}", GET_DEVICE_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        JSONArray dataArray = resultObject.getJSONArray("data");
        List<DeviceDaHuaDTO> deviceDaHuaDTOList = new ArrayList<>();
        dataArray.forEach(data->{
            JSONObject dataObject = JSON.parseObject(data.toString());
            DeviceDaHuaDTO deviceDaHuaDTO = new DeviceDaHuaDTO();
            if(Integer.parseInt(dataObject.getString("status"))>0){
                deviceDaHuaDTO.setIsDeviceOnline(true);
            }
            else{
                deviceDaHuaDTO.setIsDeviceOnline(false);
            }
            deviceDaHuaDTO.setChannelId("xuni"+dataObject.getString("id"));
            deviceDaHuaDTO.setChannelName(dataObject.getString("name"));
            deviceDaHuaDTOList.add(deviceDaHuaDTO);
        });
        return deviceDaHuaDTOList;
    }
}
